package com.smzd.framework.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthCode {
    private static final String charTable = "345679acdefghkmnprstuvwxyACDEFGHJKLMNPQRSTUVWXY";
    private static final Color[] COLORS = { new Color(0x55, 0x55, 0x55), new Color(0xfa, 0xac, 0x18),
            new Color(0x6c, 0xbe, 0x42), new Color(0x58, 0xba, 0xe9) };
    private static Random randomObj = new Random();

    private String sessionKey = "com.xtwl.commons.components.AUTHCODE";

    public Color getRandColor() {
        int i = randomObj.nextInt(COLORS.length);
        return COLORS[i];
    }

    public Color getRandColor(int s, int e) {
        Random random = new Random();
        if (s > 255)
            s = 255;
        if (e > 255)
            e = 255;
        int r = s + random.nextInt(e - s);
        int g = s + random.nextInt(e - s);
        int b = s + random.nextInt(e - s);
        return new Color(r, g, b);
    }

    public Color getRandColor(int total) {
        int[] rgb = { -1, -1, -1 };
        int value = total / 3;
        if (value > 255) {
            value = 240 + randomObj.nextInt(15);
        }
        int index = randomObj.nextInt(3);
        rgb[index] = value;
        total -= value;
        for (int i = 0; i < 3; i++) {
            if (rgb[i] == -1) {
                value = randomObj.nextInt(total);
                if (value > 255) {
                    value = 240 + randomObj.nextInt(15);
                }
                rgb[i] = value;
                break;
            }
        }
        value = total - value;
        if (value > 255) {
            value = 240 + randomObj.nextInt(15);
        }
        for (int i = 0; i < 3; i++) {
            if (rgb[i] == -1) {
                rgb[i] = value;
            }
        }

        return new Color(rgb[0], rgb[1], rgb[2]);
    }

    public String generateAuthCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return generateAuthCode(request, response, 200, 60);
    }

    public String generateAuthCode(HttpServletRequest request, HttpServletResponse response, int width, int height)
            throws Exception {
        // 禁止缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "No-cache");
        response.setDateHeader("Expires", 0);
        // 指定生成的响应是图片
        response.setContentType("image/jpeg");

        int paddingTop = Math.round(height * 0.05f);
        int size = height - paddingTop;
        int paddingWidth = Math.round(width * 0.05f);
        int w = (width - paddingWidth * 2) / 4;
        if (w > size / 2) {
            paddingWidth += (w - size / 2) / 2;
        }

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 创建BufferedImage类的对象
        Graphics g = image.getGraphics(); // 创建Graphics类的对象
        // Graphics2D g2d = (Graphics2D) g; // 通过Graphics类的对象创建一个Graphics2D类的对象
        Random random = new Random(); // 实例化一个Random对象
        Font mFont = new Font("Consolas", Font.PLAIN, size); // 通过Font构造字体
        g.setColor(Color.WHITE); // 改变图形的当前颜色为随机生成的颜色
        g.fillRect(0, 0, width, height); // 绘制一个填色矩形

        // // 画一条折线
        // BasicStroke bs = new BasicStroke(2f, BasicStroke.CAP_BUTT,
        // BasicStroke.JOIN_BEVEL); // 创建一个供画笔选择线条粗细的对象
        // g2d.setStroke(bs); // 改变线条的粗细
        // g.setColor(getRandColor(400)); // 设置当前颜色为预定义颜色中的深灰色
        // int[] xPoints = new int[3];
        // int[] yPoints = new int[3];
        // for (int j = 0; j < 3; j++) {
        // xPoints[j] = random.nextInt(width - 1);
        // yPoints[j] = random.nextInt(height - 1);
        // }
        // g.drawPolyline(xPoints, yPoints, 3);
        // 生成并输出随机的验证文字
        g.setFont(mFont);
        String sRand = "";
        for (int i = 0; i < 4; i++) {
            int idx = random.nextInt(charTable.length());
            char ctmp = charTable.charAt(idx);
            sRand += String.valueOf(ctmp);
            Color color = getRandColor();
            g.setColor(color);
            /**** 随机缩放文字并将文字旋转指定角度 **/
            // // 将文字旋转指定角度
            // Graphics2D g2d_word = (Graphics2D) g;
            // AffineTransform trans = new AffineTransform();
            // int rInt = random.nextInt(45);
            // trans.rotate(rInt * 3.14 / 180, 40 * i + 25, 30);
            // // 缩放文字
            // g2d_word.setTransform(trans);
            /************************/
            g.drawString(String.valueOf(ctmp), w * i + paddingWidth, (height - paddingTop) * 4 / 5);
            // // 转回来
            // trans.rotate(-rInt * 3.14 / 180, 40 * i + 25, 30);
        }
        g.dispose();
        // 将生成的验证码保存到Session中
        HttpSession session = request.getSession(true);
        session.setAttribute(sessionKey, sRand);
        ImageIO.write(image, "JPEG", response.getOutputStream());
        response.getOutputStream().flush();
        return sRand;
    }

    public String getSessionKey() {
        return sessionKey;
    }

    public void setSessionKey(String sessionKey) {
        this.sessionKey = sessionKey;
    }
}